package cn.lgs.com.mobileplayer.http;

import android.content.Context;
import android.support.annotation.NonNull;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import cn.lgs.com.mobileplayer.utils.LogUtil;
import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Http网络请求封装类
 * Created by lgs on 2017/8/7.
 */

public class RetrofitUtils {

    private static RetrofitUtils mRetrofitUtils;
    private static Retrofit mRetrofit;

    private RetrofitUtils(final Context context) {

        Gson gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                .create();

        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(@NonNull String message) {
                LogUtil.i("log: " + message);
            }
        });
        //打印http的body体
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        Interceptor interceptor = new Interceptor() {
            @Override
            public Response intercept(@NonNull Chain chain) throws IOException {
                Request request = chain.request();
                //缓存
                if (NetCheckUtils.checkNetwork(context) == NetCheckUtils.NO_NETWORK) {
                    request = request.newBuilder()
                            .cacheControl(CacheControl.FORCE_CACHE)
                            .build();
                    LogUtil.i("no network");
                }
                Response response = chain.proceed(request);
                //缓存响应
                if (NetCheckUtils.checkNetwork(context) != NetCheckUtils.NO_NETWORK) {
                    //有网的时候读接口上的@Headers里的配置，你可以在这里进行统一的设置
                    String cacheControl = request.cacheControl().toString();
                    LogUtil.i("cacheControl=====" + cacheControl);
                    return response.newBuilder()
                            .header("Cache-Control", cacheControl)
                            .removeHeader("Pragma")
                            .build();
                } else {
                    return response.newBuilder()
                            .header("Cache-Control", "public, only-if-cached, max-stale=120")
                            .removeHeader("Pragma")
                            .build();
                }
            }
        };

        //创建缓存路径
        File cacheFile = new File(context.getCacheDir(), "HttpCache");
        LogUtil.i("cacheFile=====" + cacheFile.getAbsolutePath());

        Cache cache = new Cache(cacheFile, 1024 * 1024 * 100);

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(45, TimeUnit.SECONDS)
                .writeTimeout(45, TimeUnit.SECONDS)
                .readTimeout(45, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .addInterceptor(httpLoggingInterceptor)
                .addInterceptor(interceptor)
                .cache(cache)
                .build();

        if (null == mRetrofit) {
            mRetrofit = new Retrofit.Builder()
                    .baseUrl(HttpConstants.BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .client(okHttpClient)
                    .build();
        }
    }

    public static RetrofitUtils getInstance(Context context) {
        if (null == mRetrofitUtils) {
            synchronized (RetrofitUtils.class) {
                if (null == mRetrofitUtils) {
                    mRetrofitUtils = new RetrofitUtils(context);
                }
            }
        }
        return mRetrofitUtils;
    }

    //获取相应的APIService对象
    public <T> T getApiService(Class<T> clazzService) {
        return mRetrofit.create(clazzService);
    }

    //异步callback，对一些特殊response逻辑处理
    public <D> void enquneCall(Call<BaseResponse<D>> call, final RetrofitCallBack<D> retrofitCallBack, final Context context) {
        call.enqueue(new Callback<BaseResponse<D>>() {
            @Override
            public void onResponse(Call<BaseResponse<D>> call, retrofit2.Response<BaseResponse<D>> response) {
                BaseResponse<D> body = response.body();
                if (null == body) {
                    Toast.makeText(context, "", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (body.getResultCode() == 2000 || body.getResultCode() == 2001 || body.getResultCode() == 2002) {
                    Toast.makeText(context, "code=====" + body.getResultCode(), Toast.LENGTH_SHORT).show();
                }
                if (body.getResultCode() == 200) {
                    retrofitCallBack.onSuccess(body);
                } else {
                    if (null != retrofitCallBack) {
                        retrofitCallBack.onFailure(body.getErrMsg());
                    }
                }
            }

            @Override
            public void onFailure(@NonNull Call<BaseResponse<D>> call, @NonNull Throwable t) {
                if (null != retrofitCallBack) {
                    retrofitCallBack.onFailure(t.toString());
                }
            }
        });
    }

    //异步特殊处理后回调
    public interface RetrofitCallBack<D> {
        void onSuccess(BaseResponse<D> baseResponse);

        void onFailure(String error);
    }
}
